<template>
  <view class="goods-list">
    <!-- 顶部操作栏 -->
    <view class="header">
      <view class="header-action" @click="addGoods">
        <uni-icons type="plus" size="20" color="#fff"></uni-icons>
        <text class="action-text">添加商品</text>
      </view>
    </view>

    <!-- Tab切换 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'all' }"
        @click="switchTab('all')"
      >
        <text class="tab-text">全部</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === '0' }"
        @click="switchTab('0')"
      >
        <text class="tab-text">种植业</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === '1' }"
        @click="switchTab('1')"
      >
        <text class="tab-text">养殖业</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === '2' }"
        @click="switchTab('2')"
      >
        <text class="tab-text">畜牧业</text>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-container">
      <view class="search-box">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          class="search-input" 
          v-model="searchKey" 
          placeholder="搜索商品名称"
          @input="onSearch"
        />
      </view>
    </view>

    <!-- 商品列表 -->
    <scroll-view 
      class="goods-scroll" 
      scroll-y 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="goods-items">
        <view 
          class="goods-item" 
          v-for="item in goodsList" 
          :key="item.goodsId"
          @click="viewDetail(item)"
        >
          <view class="item-header">
            <view class="category-tag" :class="[
              item.goodsCategory === '0' ? 'tag-green' : '',
              item.goodsCategory === '1' ? 'tag-orange' : '',
              item.goodsCategory === '2' ? 'tag-blue' : ''
            ]">
              <text class="tag-text">{{ getCategoryText(item.goodsCategory) }}</text>
            </view>
            <view class="item-actions">
              <uni-icons type="compose" size="18" color="#1890ff" @click.stop="editGoods(item)"></uni-icons>
              <uni-icons type="trash" size="18" color="#ff4d4f" @click.stop="confirmDelete(item)" style="margin-left: 20rpx;"></uni-icons>
            </view>
          </view>
          
          <view class="item-content">
            <text class="goods-name">{{ item.goodsName }}</text>
            <view class="goods-info">
              <text class="info-label">单位：</text>
              <text class="info-value">{{ item.unit }}</text>
            </view>
            <view class="goods-info" v-if="item.fullOrigin || getFullOrigin(item)">
              <text class="info-label">产地：</text>
              <text class="info-value">{{ item.fullOrigin || getFullOrigin(item) }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="goodsList.length === 0 && !loading">
        <image src="/static/images/empty.png" class="empty-image"></image>
        <text class="empty-text">暂无商品</text>
        <view class="empty-action" @click="addGoods">
          <uni-icons type="plus" size="16" color="#1890ff"></uni-icons>
          <text class="empty-action-text">添加商品</text>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="goodsList.length > 0">
        <text class="load-more-text">{{ hasMore ? '上拉加载更多' : '没有更多了' }}</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { myGoodsList, delGoods } from '@/api/business/goods.js'

export default {
  data() {
    return {
      activeTab: 'all',
      searchKey: '',
      goodsList: [],
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      refreshing: false
    }
  },
  onLoad() {
    this.loadGoods()
  },
  onShow() {
    // 从添加页面返回时刷新列表
    if (this.needRefresh) {
      this.needRefresh = false
      this.onRefresh()
    }
  },
  methods: {
    // 切换Tab
    switchTab(tab) {
      this.activeTab = tab
      this.pageNum = 1
      this.goodsList = []
      this.loadGoods()
    },

    // 搜索
    onSearch() {
      this.pageNum = 1
      this.goodsList = []
      this.loadGoods()
    },

    // 加载商品列表
    async loadGoods() {
      if (this.loading) return
      
      this.loading = true
      try {
        const response = await myGoodsList()
        
        if (response.code === 200) {
          let list = response.data || []
          
          // 根据tab筛选分类
          if (this.activeTab !== 'all') {
            list = list.filter(item => item.goodsCategory === this.activeTab)
          }
          
          // 根据搜索关键词筛选
          if (this.searchKey) {
            list = list.filter(item => 
              item.goodsName && item.goodsName.includes(this.searchKey)
            )
          }
          
          this.goodsList = list
          this.hasMore = false // 因为是全量数据，不需要分页
        }
      } catch (error) {
        console.error('加载商品列表失败:', error)
        this.goodsList = []
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },

    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.pageNum = 1
      this.goodsList = []
      this.loadGoods()
    },

    // 加载更多
    loadMore() {
      if (!this.hasMore || this.loading) return
      this.pageNum++
      this.loadGoods()
    },

    // 添加商品
    addGoods() {
      this.needRefresh = true
      uni.navigateTo({
        url: '/pages/goods/add'
      })
    },

    // 编辑商品
    editGoods(item) {
      this.needRefresh = true
      uni.navigateTo({
        url: `/pages/goods/edit?id=${item.goodsId}`
      })
    },

    // 查看详情
    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/goods/detail?id=${item.goodsId}`
      })
    },

    // 确认删除
    confirmDelete(item) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除商品"${item.goodsName}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            await this.deleteGoods(item.goodsId)
          }
        }
      })
    },

    // 删除商品
    async deleteGoods(goodsId) {
      try {
        const response = await delGoods(goodsId)
        if (response.code === 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
          // 从列表中移除删除的商品
          this.goodsList = this.goodsList.filter(item => item.goodsId !== goodsId)
        } else {
          uni.showToast({
            title: response.msg || '删除失败',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        console.error('删除商品失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 获取分类文本
    getCategoryText(category) {
      const categoryMap = {
        '0': '种植业',
        '1': '养殖业',
        '2': '畜牧业'
      }
      return categoryMap[category] || '未知'
    },

    // 获取分类样式
    getCategoryClass(category) {
      const classMap = {
        '0': 'planting',
        '1': 'breeding',
        '2': 'livestock'
      }
      return classMap[category] || ''
    },

    // 获取完整产地
    getFullOrigin(item) {
      let origin = []
      if (item.originProvince) origin.push(item.originProvince)
      if (item.originCity) origin.push(item.originCity)
      if (item.originDistrict) origin.push(item.originDistrict)
      return origin.join(' ')
    }
  }
}
</script>

<style scoped>
.goods-list {
  background-color: #f5f5f5;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部操作栏 */
.header {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.header-action {
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
}

.action-text {
  color: #fff;
  font-size: 28rpx;
  margin-left: 8rpx;
}

/* Tab切换 */
.tabs {
  background-color: #fff;
  display: flex;
  height: 88rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.tab-text {
  font-size: 30rpx;
  color: #666;
  transition: all 0.3s;
}

.tab-item.active .tab-text {
  color: #52c41a;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #52c41a;
}

/* 搜索框 */
.search-container {
  padding: 20rpx;
  background-color: #fff;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 32rpx;
  padding: 16rpx 30rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  margin-left: 16rpx;
}

/* 商品列表 */
.goods-scroll {
  flex: 1;
  background-color: #f5f5f5;
}

.goods-items {
  padding: 20rpx;
}

.goods-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.category-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.category-tag.planting {
  background-color: #f0f9ff;
  color: #1890ff;
}

.category-tag.breeding {
  background-color: #f6ffed;
  color: #52c41a;
}

.category-tag.livestock {
  background-color: #fff7e6;
  color: #fa8c16;
}

.tag-text {
  font-size: 24rpx;
}

.item-actions {
  display: flex;
  align-items: center;
}

.item-content {
  display: flex;
  flex-direction: column;
}

.goods-name {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
}

.goods-info {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.info-label {
  font-size: 26rpx;
  color: #999;
  margin-right: 10rpx;
}

.info-value {
  font-size: 26rpx;
  color: #666;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.empty-action {
  display: flex;
  align-items: center;
  padding: 20rpx 40rpx;
  border: 2rpx solid #1890ff;
  border-radius: 40rpx;
}

.empty-action-text {
  color: #1890ff;
  font-size: 28rpx;
  margin-left: 8rpx;
}

/* 加载更多 */
.load-more {
  padding: 30rpx;
  text-align: center;
}

.load-more-text {
  font-size: 26rpx;
  color: #999;
}
</style>